package com.youi.third.wechat.util;

import java.io.IOException;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.youi.util.LogUtil;

/**
 * 微信提现
 * @author kang
 */
public class WithdrawUtil {
	
	private String appid;		//微信分配的小程序ID
	private String mch_id ;      //商户号
	private String spbill_create_ip ;    //终端IP
	public String apiCert ;      //密钥
	public String server_realm_address ;      //服务器地址
	private String withdraw_url ;         //提现的url
	
    public CertHttpUtil certHttpUtil;
    
    /**
    * @param openid       微信小程序对用户的唯一标识
    * @param money        提现金额
    * @param partner_trade_no      商户订单号
    * @param desc  备注
    * @return
    */
   public String wxSendWallet(String openid, Double money, String partner_trade_no, String desc){
       Double  realPrice = money * 100;  //微信以分为单位所以要乘100，要转成int类型
       SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
       packageParams.put("mch_appid", appid);
       packageParams.put("mchid", mch_id);
       packageParams.put("nonce_str",System.currentTimeMillis());   //时间戳
       packageParams.put("desc", desc);                    //备注
       packageParams.put("partner_trade_no", partner_trade_no);    //商户订单号
       packageParams.put("amount", realPrice.intValue());          //价格
       packageParams.put("check_name", "NO_CHECK");        //NO_CHECK：不校验真实姓名; FORCE_CHECK：强校验真实姓名
       packageParams.put("openid", openid);        //openid
       packageParams.put("spbill_create_ip", "119.23.76.190");        //该IP同在商户平台设置的IP白名单中的IP没有关联，该IP可传用户端或者服务端的IP
       //获取sign
       String sign = WechatUtil.createSign("UTF-8", packageParams, apiCert);//最后这个是自己设置的32位密钥
       packageParams.put("sign", sign);

       //转成XML
       String requestXML = WeChatXmlUtil.getRequestXml(packageParams);

       //得到含有prepay_id的XML
       String resXml = null;
       try {
           resXml = certHttpUtil.postData(withdraw_url, requestXML);
       } catch (Exception e) {
           e.printStackTrace();
       }

       //解析XML存入Map
       Map map = null;
       try {
           map = WithdrawXmlUtil.doXMLParse(resXml);
       } catch (JDOMException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }

       String returnCode = (String)map.get("return_code");
       if("SUCCESS".equals(returnCode)){
           if ("SUCCESS".equals(map.get("result_code"))){
        	   LogUtil.Info("提现成功");
               // 这里是提现成功
               return "提现成功";
           }
           LogUtil.Info((String)map.get("return_msg"));
           return null;
       }else {
           LogUtil.Info((String)map.get("return_msg"));
           return null;
       }
   }

}
